import ftplib
import os
import json

def filesync_byftp(ftp_host,ftp_port,ftp_user,ftp_password,remote_directory,local_directory):
    # # 机器 A 的 FTP 服务器信息
    # ftp_host = 'your_ftp_host'
    # ftp_user = 'your_ftp_user'
    # ftp_password = 'your_ftp_password'
    # # 机器 A 上要备份的目录
    # remote_directory = '/path/to/remote/directory'
    # # 机器 B 上保存备份文件的目录
    # local_directory = '/path/to/local/directory'
    # 用于记录文件信息的文件
    #小批量还行  大批量应该在不同目录下做配资文件？
    #无配置文件应该动态判断  并僧成新的配置文件
    # info_file = os.path.join(local_directory, 'file_info.json')



    # if os.path.exists(info_file):
    #     with open(info_file, 'r') as f:
    #         file_info = json.load(f)
    # else:
    #     file_info = {}

    try:
        # 连接到 FTP 服务器
        ftp = ftplib.FTP()
        ftp.connect(ftp_host,ftp_port)
        ftp.login(ftp_user, ftp_password)

        def traverse_remote_dir(remote_dir, local_dir):
            nonlocal ftp, file_info
            # 切换到当前远程目录
            # remote_dir=os.path.abspath(remote_dir)
            ftp.cwd(remote_dir)
            # 获取当前远程目录下的详细文件和目录列表
            lines = []
            ftp.dir('.', lines.append)

            new_file_info = {}
            for line in lines:
                parts = line.split()
                item = parts[-1]
                is_file = not line.startswith('d')
                if is_file:
                    # 处理文件
                    ftp.sendcmd('TYPE I')
                    # remote_mtime = ftp.sendcmd(f'MDTM {item}').split()[1]
                    local_file_path = os.path.join(local_dir, item)
                    if os.path.exists(local_file_path):
                        remote_size = ftp.size(item)
                        local_size=os.path.getsize(local_file_path)
                        if remote_size!=local_size:
                            full_remote_path = remote_dir + "/" + item
                            with open(local_file_path, 'wb') as local_file:
                                ftp.retrbinary('RETR ' + item, local_file.write)
                            print(f"更新文件: {full_remote_path}")
                    else:
                        full_remote_path = remote_dir+"/"+item
                        with open(local_file_path, 'wb') as local_file:
                            ftp.retrbinary('RETR ' + item, local_file.write)
                        print(f"增加文件: {full_remote_path}")
                else:
                    # 处理子目录
                    new_remote_dir = remote_dir+"/"+item
                    new_local_dir = os.path.join(local_dir, item)
                    if not os.path.exists(new_local_dir):
                        os.makedirs(new_local_dir)
                    traverse_remote_dir(new_remote_dir, new_local_dir)


        # 创建本地根目录（如果不存在）
        if not os.path.exists(local_directory):
            os.makedirs(local_directory)
        traverse_remote_dir(remote_directory, local_directory)

        # # 保存新的文件信息
        # with open(info_file, 'w') as f:
        #     json.dump(new_file_info, f)

        print("备份完成")

        # 关闭 FTP 连接
        ftp.quit()
    except Exception as e:
        print(f"备份过程中出现错误: {e}")